package ntd.util.frame.task.handle;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.Entity;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.StaticLog;
import ntd.task.Task;
import ntd.task.bo.TaskInfo;
import ntd.util.config.common.enums.app.EnumServerAppType;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.data.tool.ToolMysql;
import ntd.util.frame.server.ServerManager;
import ntd.util.frame.server.context.ContextServer;
import ntd.util.util.ToolDuration;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerManagerService implements Task {

    @Override
    public TaskInfo info() {
        return new TaskInfo("任务-服务应用同步", "task-server-app-sync", new ServerManagerService());
    }

    public Map<String, Entity> cache = new HashMap<>();

    @Override
    public void execute(Object o) {
        ToolDuration.duration(this::handle, "任务-服务应用同步");
    }

    public void handle() {
        // 查询服务应用列表
        ToolMysql toolMysql = new ToolMysql(FactoryData.dataSource());
        try {
            List<Entity> functionServerApps = toolMysql.db.findAll(new Entity("function_server_app"));
            functionServerApps.forEach(this::init);
        } catch (SQLException e) {
            StaticLog.error(e, "[服务管理][初始化][{}]失败...");
            throw new RuntimeException(e);
        }
    }

    /**
     * 应用初始化
     * @param functionServerApp
     */
    public void init(Entity functionServerApp) {
        String id = functionServerApp.getStr("id");
        // 应用缓存
        Entity entity = cache.get(id);
        if (ObjectUtil.isNull(entity) || DateUtil.compare(functionServerApp.getDate("updated_date"), entity.getDate("updated_date")) != 0) {
            // 初始化
            ContextServer contextServer = new ContextServer();
            contextServer.setCode(functionServerApp.getStr("id"));
            contextServer.setPort(functionServerApp.getInt("port"));
            contextServer.setEnumServerAppType(EnumServerAppType.valueOf(functionServerApp.getStr("enum_server_app_type")));

            SpringUtil.getBean(ServerManager.class).init(contextServer);
            // 更新缓存
            cache.put(id, functionServerApp);
        }
    }
}
